﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Xiaowei.Models;

namespace Xiaowei
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {

        ApplicationModel ApplicationModel => ApplicationModel.Instance;

        protected override void OnExit(ExitEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
            base.OnExit(e);
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            NamedPipeClientStream clientStream = new NamedPipeClientStream("XiaoweiPipe");
            try
            {
                clientStream.Connect(1);
                if (clientStream.IsConnected)
                {
                    using (StreamWriter sw = new StreamWriter(clientStream))
                    {
                        foreach (var item in e.Args)
                        {
                            sw.Write(item+"\t");
                            sw.Flush();
                        }
                        Shutdown();
                        return;
                    } 

                }
            }
            catch (TimeoutException ex)
            {
                
                _=Task.Run(() => {
                    var a = ex;
                    while (true)
                    {
                        NamedPipeServerStream serverStream = new NamedPipeServerStream("XiaoweiPipe");
                        serverStream.WaitForConnection();
                        using (StreamReader sr = new StreamReader(serverStream))
                        {
                            Trace.WriteLine(sr.ReadLine());
                            Trace.WriteLine("\n");
                        }
                    }

                });
            }
            Task.Run(async ()=>{
                await ApplicationModel.TryReadDebugFileAsync();
                ApplicationModel.InitService();
                ApplicationModel.Instance.PlayResponseAndSystemTTS(Audios.IsLoading);
            });

            base.OnStartup(e);
        }
    }
}
